package com.cyt.web.controller.phone;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.ErrorCode;
import com.cyt.base.util.ServletUtils;
import com.cyt.base.util.StringUtils;
import com.cyt.sys.model.po.SysDictContent;
import com.cyt.sys.service.SysDictContentService;
import com.cyt.web.controller.base.PhoneController;
import com.cyt.work.association.model.vo.WxAssociationSignVo;
import com.cyt.work.association.service.WxAssociationNewStuService;
import com.cyt.work.association.service.WxAssociationSignService;
import com.cyt.work.enrollment.model.po.EnrollmentRelease;
import com.cyt.work.enrollment.model.po.EnrollmentStuinfo;
import com.cyt.work.enrollment.model.vo.EnrollmentDictVo;
import com.cyt.work.enrollment.model.vo.EnrollmentReleaseVo;
import com.cyt.work.enrollment.model.vo.EnrollmentStuinfoVo;
import com.cyt.work.enrollment.service.*;
import com.cyt.wx.model.po.WxEducationUser;
import com.cyt.wx.model.po.WxMember;
import com.cyt.wx.model.vo.WxEducationUserVo;
import com.cyt.wx.service.WxEducationUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

/**
 * 自主招生--移动端api接口
 *
 * @author caideyong
 * @date 2019-11-26
 */
@RestController
public class PhoneEnrollmentController extends PhoneController {

    @Autowired
    private EnrollmentHomeinfoService enrollmentHomeinfoService;
    @Autowired
    private EnrollmentReleaseService enrollmentReleaseService;
    @Autowired
    private EnrollmentRuleService enrollmentRuleService;
    @Autowired
    private EnrollmentStuinfoService enrollmentStuinfoService;
    @Autowired
    private EnrollmentTestService enrollmentTestService;

    @Resource
    private SysDictContentService sysDictContentService;

    /**
     * 首页
     * @param token
     * @param applyId
     * @author cuibiming
     * @date 2019/11/26 08:50
     */
    @RequestMapping(value = "/phone/enrollment/enrollmentEdit")
    public ModelAndView index(String id,String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView("/mobile/enrollment/enrollmentIndex");

        EnrollmentReleaseVo enrollmentReleaseVo = new EnrollmentReleaseVo();
        enrollmentReleaseVo.setId(id);
        List<EnrollmentRelease> enrollmentReleaseList = enrollmentReleaseService.listExample(enrollmentReleaseVo);
        if (enrollmentReleaseList != null && enrollmentReleaseList.size() > 0) {
            EnrollmentRelease enrollmentRelease = enrollmentReleaseList.get(0);
            enrollmentRelease.setStartTimeStr(DateUtil.formatDateTime(enrollmentRelease.getStartTime()));
            enrollmentRelease.setEndTimeStr(DateUtil.formatDateTime(enrollmentRelease.getEndTime()));
            modelAndView.addObject("enrollmentRelease", enrollmentRelease);
        }

        modelAndView.addObject("releaseId", id);
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 自主招生--查询招生简章状态
     *
     * @param enrollmentReleaseVo 传入参数对象
     * @return ReturnResult
     * @author caideyong
     * @date 2019/11/26
     */
    @RequestMapping(value = "/phone/enrollment/checkState", method = RequestMethod.POST)
    public ReturnResult checkState(EnrollmentReleaseVo enrollmentReleaseVo) {
        List<EnrollmentRelease> enrollmentReleaseList = enrollmentReleaseService.listExample(enrollmentReleaseVo);
        if (enrollmentReleaseList != null && enrollmentReleaseList.size() > 0) {
            EnrollmentRelease enrollmentRelease = enrollmentReleaseList.get(0);
            enrollmentRelease.setStartTimeStr(DateUtil.formatDateTime(enrollmentRelease.getStartTime()));
            enrollmentRelease.setEndTimeStr(DateUtil.formatDateTime(enrollmentRelease.getEndTime()));
            if (enrollmentRelease.getState().equals("1")) {
                return new ReturnResult(ErrorCode.CODE_1, "该招生未发布，无法报名！");
            } else if (enrollmentRelease.getState().equals("3")) {
                return new ReturnResult(ErrorCode.CODE_1, "该招生已结束，无法报名！");
            } else if (enrollmentRelease.getState().equals("2") && (new Date().before(enrollmentRelease.getStartTime()))) {
                return new ReturnResult(ErrorCode.CODE_1, "该招生未开始，无法报名！");
            } else if (enrollmentRelease.getState().equals("2") && (new Date().after(enrollmentRelease.getEndTime()))) {
                enrollmentRelease.setState("3");
                enrollmentRelease.setUpdateTime(new Date());
                enrollmentReleaseService.updateByPrimaryKey(enrollmentRelease);
                return new ReturnResult(ErrorCode.CODE_1, "该招生已结束，无法报名！");
            } else {
                return new ReturnResult(enrollmentRelease);
            }
        } else {
            //失败,未查询到该学生报名信息
            return new ReturnResult(ErrorCode.CODE_1, "未查询到此次招生简章！");
        }
    }

    /**
     * 招生总章页面
     * @param token
     * @param applyId
     * @author cuibiming
     * @date 2019/11/26 08:50
     */
    @RequestMapping(value = "/phone/enrollment/rule")
    public ModelAndView toRulePage(String releaseId,String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView("/mobile/enrollment/enrollmentRule");

        EnrollmentReleaseVo enrollmentReleaseVo = new EnrollmentReleaseVo();
        enrollmentReleaseVo.setId(releaseId);
        List<EnrollmentRelease> enrollmentReleaseList = enrollmentReleaseService.listExample(enrollmentReleaseVo);
        if (enrollmentReleaseList != null && enrollmentReleaseList.size() > 0) {
            EnrollmentRelease enrollmentRelease = enrollmentReleaseList.get(0);
            enrollmentRelease.setStartTimeStr(DateUtil.formatDateTime(enrollmentRelease.getStartTime()));
            enrollmentRelease.setEndTimeStr(DateUtil.formatDateTime(enrollmentRelease.getEndTime()));
            modelAndView.addObject("enrollmentRelease", enrollmentRelease);
        }

        modelAndView.addObject("releaseId", releaseId);
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 照片采集页面
     * @param token
     * @param applyId
     * @author cuibiming
     * @date 2019/11/26 08:50
     */
    @RequestMapping(value = "/phone/enrollment/infoPhoto")
    public ModelAndView toRegisterInfoPhotoPage(String releaseId,String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView("/mobile/enrollment/enrollmentRegisterInfoPhoto");
        modelAndView.addObject("releaseId", releaseId);
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 基础信息页面
     * @param token
     * @param applyId
     * @author cuibiming
     * @date 2019/11/26 08:50
     */
    @RequestMapping(value = "/phone/enrollment/infoBase")
    public ModelAndView toRegisterInfoBasePage(String photoObjectId,String releaseId, String token, String applyId) {
        if(!StringUtils.isEmpty(photoObjectId)){
            ServletUtils.getSession().setAttribute("infoPhoto",photoObjectId);
        }
        ModelAndView modelAndView = new ModelAndView("/mobile/enrollment/enrollmentRegisterInfoBase");

        modelAndView.addObject("genderList", getDicsStringByCode("sexType"));
        modelAndView.addObject("politicalStatusList", getDicsStringByCode("politicalStatus"));
        modelAndView.addObject("nationalityList", getDicsStringByCode("nationality"));
        modelAndView.addObject("accountTypeList", getDicsStringByCode("accountType"));

        modelAndView.addObject("releaseId", releaseId);
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    private String getDicsStringByCode(String dictType){
        ReturnResult returnResult = sysDictContentService.listByCode(dictType);
        List<EnrollmentDictVo> returnDicts = new ArrayList<>();
        if(ErrorCode.CODE_0 == returnResult.getCode()){
            List<SysDictContent> returnDatas = (List<SysDictContent>) returnResult.getData();
            if(null != returnDatas && returnDatas.size()>0){
                for(int i=0;i<returnDatas.size();i++){
                    EnrollmentDictVo vo = new EnrollmentDictVo();
                    vo.setTitle(returnDatas.get(i).getName());
                    vo.setValue(returnDatas.get(i).getValue());
                    returnDicts.add(vo);
                }
            }
        }

        return JSON.toJSONString(returnDicts);
    }

    /**
     * 学校信息页面
     * @param token
     * @param applyId
     * @author cuibiming
     * @date 2019/11/26 08:50
     */
    @RequestMapping(value = "/phone/enrollment/infoSchool")
    public ModelAndView toRegisterInfoSchoolPage(String name, String gender,String genderValue,
                                                 String politicalStatus,String politicalStatusValue,
                                                 String nationality,String nationalityValue,
                                                 String accountType,String accountTypeValue,
                                               String phonenum, String cardnum,String releaseId,String token, String applyId) {
        HttpSession session = ServletUtils.getSession();
        if(!StringUtils.isEmpty(name)){
            session.setAttribute("infoName",name);
        }
        if(!StringUtils.isEmpty(gender)){
            session.setAttribute("infoGender",gender);
            session.setAttribute("infoGenderValue",genderValue);
        }
        if(!StringUtils.isEmpty(politicalStatus)){
            session.setAttribute("infoPoliticalStatus",politicalStatus);
            session.setAttribute("infoPoliticalStatusValue",politicalStatusValue);
        }
        if(!StringUtils.isEmpty(nationality)){
            session.setAttribute("infoNationality",nationality);
            session.setAttribute("infoNationalityValue",nationalityValue);
        }
        if(!StringUtils.isEmpty(accountType)){
            session.setAttribute("infoAccountType",accountType);
            session.setAttribute("infoAccountTypeValue",accountTypeValue);
        }
        if(!StringUtils.isEmpty(phonenum)){
            session.setAttribute("infoPhonenum",phonenum);
        }
        if(!StringUtils.isEmpty(cardnum)){
            session.setAttribute("infoCardnum",cardnum);
        }

        ModelAndView modelAndView = new ModelAndView("/mobile/enrollment/enrollmentRegisterInfoSchool");
        modelAndView.addObject("releaseId", releaseId);
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 家庭信息页面
     * @param token
     * @param applyId
     * @author cuibiming
     * @date 2019/11/26 08:50
     */
    @RequestMapping(value = "/phone/enrollment/infoFamily")
    public ModelAndView toRegisterInfoFamilyPage(String schoolName, String schoolAddress, String address, String testNum,
                                               String postalCode, String gradePersonNum, String classPersonNum, String addressAndPhone,
                                                 String releaseId,String token, String applyId) {
        HttpSession session = ServletUtils.getSession();
        if(!StringUtils.isEmpty(schoolName)){
            session.setAttribute("infoSchoolName",schoolName);
        }
        if(!StringUtils.isEmpty(schoolAddress)){
            session.setAttribute("infoSchoolAddress",schoolAddress);
        }
        if(!StringUtils.isEmpty(address)){
            session.setAttribute("infoAddress",address);
        }
        if(!StringUtils.isEmpty(testNum)){
            session.setAttribute("infoTestNum",testNum);
        }
        if(!StringUtils.isEmpty(postalCode)){
            session.setAttribute("infoPostalCode",postalCode);
        }
        if(!StringUtils.isEmpty(gradePersonNum)){
            session.setAttribute("infoGradePersonNum",gradePersonNum);
        }
        if(!StringUtils.isEmpty(classPersonNum)){
            session.setAttribute("infoClassPersonNum",classPersonNum);
        }
        if(!StringUtils.isEmpty(addressAndPhone)){
            session.setAttribute("infoAddressAndPhone",addressAndPhone);
        }
        ModelAndView modelAndView = new ModelAndView("/mobile/enrollment/enrollmentRegisterInfoFamily");
        modelAndView.addObject("releaseId", releaseId);
        modelAndView.addObject("genderList", getDicsStringByCode("sexType"));
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 成绩信息页面
     * @param token
     * @param applyId
     * @author cuibiming
     * @date 2019/11/26 08:50
     */
    @RequestMapping(value = "/phone/enrollment/infoGrade")
    public ModelAndView toRegisterInfoGradePage(String homeInfo,String releaseId, String token, String applyId) {
        HttpSession session = ServletUtils.getSession();
        if(!StringUtils.isEmpty(homeInfo)){
            session.setAttribute("homeInfo",homeInfo);
        }
        ModelAndView modelAndView = new ModelAndView("/mobile/enrollment/enrollmentRegisterInfoGrade");
        modelAndView.addObject("releaseId", releaseId);
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 获奖信息页面
     * @param token
     * @param applyId
     * @author cuibiming
     * @date 2019/11/26 08:50
     */
    @RequestMapping(value = "/phone/enrollment/infoAward")
    public ModelAndView toRegisterInfoAwardPage(String testInfo,String releaseId,String token, String applyId) {
        HttpSession session = ServletUtils.getSession();
        if(!StringUtils.isEmpty(testInfo)){
            session.setAttribute("testInfo",testInfo);
        }
        ModelAndView modelAndView = new ModelAndView("/mobile/enrollment/enrollmentRegisterInfoAward");
        modelAndView.addObject("releaseId", releaseId);
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 提交
     *
     * @param awardInfo 获奖情况
     * @return ReturnResult
     * @author caideyong
     * @date 2019-11-22 16:30:39
     */
    @RequestMapping(value = "/phone/enrollment/submit", method = RequestMethod.POST)
    public ReturnResult addOrUpdate(String awardInfo,String releaseId) {
        HttpSession session = ServletUtils.getSession();
        //先保存
        session.setAttribute("awardInfo",awardInfo);

        EnrollmentStuinfoVo enrollmentStuinfoVo = new EnrollmentStuinfoVo();
        enrollmentStuinfoVo.setReleaseId(releaseId);
        enrollmentStuinfoVo.setPic((String) session.getAttribute("infoPhoto"));
        enrollmentStuinfoVo.setName((String) session.getAttribute("infoName"));
        enrollmentStuinfoVo.setSex((String) session.getAttribute("infoGenderValue"));
        enrollmentStuinfoVo.setPoliticalStatus((String) session.getAttribute("infoPoliticalStatusValue"));
        enrollmentStuinfoVo.setNationality((String) session.getAttribute("infoNationalityValue"));
        enrollmentStuinfoVo.setAccountType((String) session.getAttribute("infoAccountTypeValue"));
        enrollmentStuinfoVo.setPhone((String) session.getAttribute("infoPhonenum"));
        enrollmentStuinfoVo.setCard((String) session.getAttribute("infoCardnum"));
        enrollmentStuinfoVo.setSchool((String) session.getAttribute("infoSchoolName"));
        enrollmentStuinfoVo.setSchoolPlace((String) session.getAttribute("infoSchoolAddress"));
        enrollmentStuinfoVo.setAccountPlace((String) session.getAttribute("infoAddress"));
        enrollmentStuinfoVo.setTestNum((String) session.getAttribute("infoTestNum"));
        enrollmentStuinfoVo.setPostNum((String) session.getAttribute("infoPostalCode"));
        enrollmentStuinfoVo.setGradeNum((String) session.getAttribute("infoGradePersonNum"));
        enrollmentStuinfoVo.setClassNum((String) session.getAttribute("infoClassPersonNum"));
        enrollmentStuinfoVo.setPlace((String) session.getAttribute("infoAddressAndPhone"));
        enrollmentStuinfoVo.setHomeInfo((String) session.getAttribute("homeInfo"));
        enrollmentStuinfoVo.setTestInfo((String) session.getAttribute("testInfo"));
        enrollmentStuinfoVo.setReward(awardInfo);
        ReturnResult returnResult = enrollmentStuinfoService.addOrUpdatePhone(enrollmentStuinfoVo);
        if(ErrorCode.CODE_0 == returnResult.getCode()){
            //提交成功 清除session
            Enumeration name = session.getAttributeNames() ;
            while(name.hasMoreElements()){
                String sessionKey = name.nextElement().toString() ;
                session.removeAttribute(sessionKey) ;
            }
        }
        return returnResult;
    }

    /**
     * 获奖信息页面
     * @param token
     * @param applyId
     * @author cuibiming
     * @date 2019/11/26 08:50
     */
    @RequestMapping(value = "/phone/enrollment/result")
    public ModelAndView toRegisterResultPage(String releaseId,String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView("/mobile/enrollment/enrollmentScheduleQuery");
        modelAndView.addObject("releaseId", releaseId);
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 自主招生--查询报名进度
     *
     * @param enrollmentStuinfoVo 传入参数对象
     * @return ReturnResult
     * @author caideyong
     * @date 2019/11/26
     */
    @RequestMapping(value = "/phone/enrollment/getEnrollmentResult", method = RequestMethod.POST)
    public ReturnResult getEnrollmentResult(EnrollmentStuinfoVo enrollmentStuinfoVo) {
        List<EnrollmentStuinfo> enrollmentStuinfoVoList = enrollmentStuinfoService.listExample(enrollmentStuinfoVo);
        if (enrollmentStuinfoVoList != null && enrollmentStuinfoVoList.size() > 0) {
            EnrollmentStuinfo enrollmentStuinfo = enrollmentStuinfoVoList.get(0);
            enrollmentStuinfo.setSex("1".equals(enrollmentStuinfo.getSex())?"男":"女");
            return new ReturnResult(enrollmentStuinfo);
        } else {
            //失败,未查询到该学生报名信息
            return new ReturnResult(ErrorCode.CODE_1, "未查询到该学生招生信息！");
        }
    }

    /**
     * 自主招生--查询招生简章
     *
     * @param enrollmentReleaseVo 传入参数对象
     * @return ReturnResult
     * @author caideyong
     * @date 2019/11/26
     */
    @RequestMapping(value = "/phone/enrollment/getEnrollmentRelease", method = RequestMethod.GET)
    public ReturnResult getEnrollmentRelease(EnrollmentReleaseVo enrollmentReleaseVo) {
        List<EnrollmentRelease> enrollmentReleaseList = enrollmentReleaseService.listExample(enrollmentReleaseVo);
        if (enrollmentReleaseList != null && enrollmentReleaseList.size() > 0) {
            EnrollmentRelease enrollmentRelease = enrollmentReleaseList.get(0);
            enrollmentRelease.setStartTimeStr(DateUtil.formatDateTime(enrollmentRelease.getStartTime()));
            enrollmentRelease.setEndTimeStr(DateUtil.formatDateTime(enrollmentRelease.getEndTime()));
            return new ReturnResult(enrollmentRelease);
        } else {
            //失败,未查询到该学生报名信息
            return new ReturnResult(ErrorCode.CODE_1, "未查询到此次招生简章！");
        }
    }
}